/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.controller;

import fr.adama.dto.ModelePaieDTO;
import fr.adama.entite.modele.ModelePaie;
import fr.adama.service.ModeleBulletinPaieService;
import fr.adama.validator.ModelPaieValidator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author avisto
 */
@Controller
public class ModeleBulletinPaieController {

    private static final Logger logger = LoggerFactory.getLogger(ModeleBulletinPaieController.class);
    @Autowired
    private MessageSource messageSource;

    @Autowired
    ModeleBulletinPaieService modeleBulletinPaieService;

    @RequestMapping(method = RequestMethod.GET, value = "/modele/bulletinpaie/index.do")
    public ModelAndView index() {
        return new ModelAndView("modele/bulletinpaie/index");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/bulletinpaie/add.do")
    public String add(ModelMap model) {

        ModelePaieDTO modelpaie = new ModelePaieDTO();
        model.addAttribute("modelpaie", modelpaie);
        return "modele/bulletinpaie/add";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/modele/bulletinpaie/add.do")
    public ModelAndView insertModelPaie(@ModelAttribute("modelpaie") ModelePaieDTO modelpaie, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {

        result = new BeanPropertyBindingResult(modelpaie, "modelpaie");

        ModelPaieValidator validator = new ModelPaieValidator(messageSource);
        validator.validate(modelpaie, result);
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            map.put("modelpaie", modelpaie);
            map.put("org.springframework.validation.BindingResult.modelpaie", result);
            return new ModelAndView("modele/bulletinpaie/add", map);
        }
        try {
            logger.info("Ajout du model de paie {}", modelpaie.getNom());
            modelpaie = modeleBulletinPaieService.addModelPaie(modelpaie);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("ModelPaie.add.success", new String[]{modelpaie.getNom()}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
               logger.error("Erreur d'ajout du model de paie {}", modelpaie.getNom(),ex);
            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMEXISTMODELPAIE")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("ModelPaie.add.error.model.exist", new String[]{modelpaie.getNom()}, new Locale("fr")));
                    result.addError(error);
                    Map<String, Object> map = new HashMap<>();
                    map.put("modelpaie", modelpaie);
                    map.put("org.springframework.validation.BindingResult.modelpaie", result);
                    return new ModelAndView("modele/bulletinpaie/add", map);
                }

            } 
        }
        return new ModelAndView("redirect:/modele/bulletinpaie/show.do", "id", modelpaie.getId());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/bulletinpaie/list.do")
    public ModelAndView listModele() {
        List<ModelePaieDTO> listModel = modeleBulletinPaieService.findAll(ModelePaie.class, ModelePaieDTO.class);
        return new ModelAndView("modele/bulletinpaie/list", "listModel", listModel);

    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/bulletinpaie/show.do")
    public ModelAndView getModelById(@RequestParam(required = true, value = "id") Long id) {
        ModelePaieDTO modelPaie = modeleBulletinPaieService.getById(id, ModelePaie.class, ModelePaieDTO.class);

        return new ModelAndView("modele/bulletinpaie/show", "modelpaie", modelPaie);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/bulletinpaie/update.do")
    public ModelAndView getModelForUpdate(@RequestParam(required = true, value = "id") Long id) {
        ModelePaieDTO modelPaie = modeleBulletinPaieService.getById(id, ModelePaie.class, ModelePaieDTO.class);

        return new ModelAndView("modele/bulletinpaie/update", "modelpaie", modelPaie);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/modele/bulletinpaie/update.do")
    public ModelAndView updateModelPaie(@ModelAttribute("modelpaie") ModelePaieDTO modelpaie, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {

        result = new BeanPropertyBindingResult(modelpaie, "modelpaie");

        ModelPaieValidator validator = new ModelPaieValidator(messageSource);
        validator.validate(modelpaie, result);
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            map.put("modelpaie", modelpaie);
            map.put("org.springframework.validation.BindingResult.modelpaie", result);
            return new ModelAndView("modele/bulletinpaie/update", map);
        }
        try {
             logger.info("Mis à jour du model de paie {}", modelpaie.getNom());
            modelpaie = modeleBulletinPaieService.updateModelPaie(modelpaie);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("ModelPaie.update.success", new String[]{modelpaie.getNom()}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur de mis à jour du model de paie {}", modelpaie.getNom(),ex);
            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMEXISTMODELPAIE")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("ModelPaie.update.error.model.exist", new String[]{modelpaie.getNom()}, new Locale("fr")));
                    result.addError(error);
                    Map<String, Object> map = new HashMap<>();
                    map.put("modelpaie", modelpaie);
                    map.put("org.springframework.validation.BindingResult.modelpaie", result);
                    return new ModelAndView("modele/bulletinpaie/update", map);
                }

            } 
        }
        return new ModelAndView("redirect:/modele/bulletinpaie/show.do", "id", modelpaie.getId());
    }
}
